import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:practice_flutter/pages/home/index.dart';
import 'package:practice_flutter/pages/main/index.dart';
import 'package:practice_flutter/utils/eventbus.dart';
import 'package:practice_flutter/utils/logger.dart';
import 'package:practice_flutter/utils/token.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  @override
  void initState() {
    super.initState();
    logger.i('首页触发了');
    // 先获取token
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
    });

    //监听推出
    eventBus.on<LoginOut>().listen((event) {
      // ignore: use_build_context_synchronously
      Navigator.pushNamed(context, '/login');
    });
  }

  int currentIndex = 0;
  List tabBarList = [
    {
      "title": "首页",
      "default": "assets/tabs/home_default.png",
      "active": "assets/tabs/home_active.png"
    },
    {
      "title": "我的",
      "default": "assets/tabs/my_default.png",
      "active": "assets/tabs/my_active.png"
    }
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child: IndexedStack(
        index: currentIndex,
        children:  [const HomePage(), MainPage(currentIndex:currentIndex)],
      )),
      bottomNavigationBar: BottomNavigationBar(
        backgroundColor: Colors.white,
        type: BottomNavigationBarType.fixed,
        items: barItemList(),
        currentIndex: currentIndex,
        selectedItemColor: const Color.fromARGB(255, 85, 145, 175),
        unselectedItemColor: Colors.grey,
        onTap: (value) => (setState(() {
          currentIndex = value;
        })),
      ),
    );
  }

  List<BottomNavigationBarItem> barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var item in tabBarList) {
      items.add(
        BottomNavigationBarItem(
            icon: Image.asset(
              item['default'],
              width: 32,
              height: 32,
            ),
            activeIcon: Image.asset(
              item['active'],
              width: 32,
              height: 32,
            ),
            label: item['title']),
      );
    }
    return items;
  }
}
